<template>
	<view class="wrapper">
		<u-form label-width="200" :model="form" ref="uForm">
			<view class="column">
				<view class="flag-title light-color">基础信息</view>
				<u-form-item required :border-bottom="false" prop="storeName" label="店铺名称">
					<u-input
						v-model="form.storeName"
						:custom-style="defaultInputStyle"
						:disabled="companyData && companyData.storeDisable === 'OPEN'"
					/>
				</u-form-item>
				<u-form-item required :border-bottom="false" prop="type" label="店铺类型">
					<u-input
						:custom-style="defaultInputStyle"
						v-model="type"
						disabled
						@click="companyData && companyData.storeDisable === 'OPEN' ? '' : showType()"
						:disabled="companyData && companyData.storeDisable === 'OPEN'"
					/>
				</u-form-item>
				<u-form-item required :border-bottom="false" prop="marketIds" label="所属市场" v-if="form.type">
					<u-input
						:custom-style="defaultInputStyle"
						v-model="marketIds"
						disabled
						@click="companyData && companyData.storeDisable === 'OPEN' ? '' : showMarket()"
					/>
				</u-form-item>
				<u-form-item required :border-bottom="false" prop="goodsManagementCategory" label="店铺经营类目">
					<u-input
						:custom-style="defaultInputStyle"
						v-model="goodsManagementCategory"
						disabled
						@click="companyData && companyData.storeDisable === 'OPEN' ? '' : showCategory()"
					/>
				</u-form-item>
				<u-form-item required :border-bottom="false" prop="storeAddressPath" label="店铺所在地">
					<u-input
						:custom-style="defaultInputStyle"
						v-model="form.storeAddressPath"
						disabled
						@click="companyData && companyData.storeDisable === 'OPEN' ? '' : showPicker()"
					/>
				</u-form-item>
				<!-- <u-form-item required :border-bottom="false" prop="storeAddressPath" label="店铺定位">
					<view class="get-center" @click="clickUniMap()">开始定位</view>
					<view class="tips-success" v-if="form.storeCenter">已成功定位</view>
				</u-form-item> -->
				<u-form-item required :border-bottom="false" prop="storeAddressDetail" label="店铺详细地址">
					<u-input
						:custom-style="defaultInputStyle"
						v-model="form.storeAddressDetail"
						:disabled="companyData && companyData.storeDisable === 'OPEN'"
					/>
				</u-form-item>
				<!-- <u-form-item :border-bottom="false" prop="deliveryAddress" label="提货地址">
					<u-input :custom-style="defaultInputStyle" v-model="form.deliveryAddress" />
				</u-form-item>
				<view class="tip">若不填写提货地址，客户可选择自提点就是店铺地址</view> -->
				<u-form-item required :border-bottom="false" prop="storeDesc" label="店铺简介">
					<u-input
						type="textarea"
						:custom-style="defaultInputStyle"
						v-model="form.storeDesc"
						:disabled="companyData && companyData.storeDisable === 'OPEN'"
					/>
				</u-form-item>
				<u-form-item required :border-bottom="false" prop="storeLogo" label="店铺logo">
					<view>
						<u-upload
							:class="{ 'no-del': companyData && companyData.storeDisable === 'OPEN' }"
							:file-list="storeLogoFileList"
							:header="{ accessToken: storage.getAccessToken() }"
							:action="action"
							width="200"
							@on-uploaded="onUploaded($event, 'storeLogo')"
							:max-count="1"
							:show-progress="false"
						></u-upload>
					</view>
				</u-form-item>
			</view>
		</u-form>
		<view class="submit" @click="nextStep" v-if="companyData && companyData.storeDisable === 'OPEN'">返回</view>
		<view class="submit" @click="validatorStep1Form" v-else>提交平台审核</view>
		<m-city
			:provinceData="list"
			headTitle="区域选择"
			ref="cityPicker"
			@funcValue="getPickerParentValue"
			pickerSize="4"
		></m-city>

		<u-select v-model="enableCategory" @confirm="confirmCategory" :list="categoryList"></u-select>
		<u-select v-model="enableType" @confirm="confirmType" :list="typeList"></u-select>
		<u-popup class="cancel-popup" v-model="marketVisible" mode="bottom" length="40%">
			<view class="check-header">
				<view class="check-left" @click="cancelMarket">取消</view>
				<view class="check-right" @click="confirmMarket">确定</view>
			</view>
			<view class="check-body">
				<u-radio-group v-model="radioMarketId" @change="radioChange" v-if="form.type != '2'">
					<view>
						<view class="radio-view" v-for="(item, index) in marketList" :key="index">
							<u-radio :active-color="lightColor" label-size="25" shape="circle" :name="item.value">
								{{ item.label }}
							</u-radio>
						</view>
					</view>
				</u-radio-group>
				<u-checkbox-group @change="checkboxGroupChange" v-if="form.type == '2'">
					<view>
						<view class="radio-view" v-for="(item, index) in marketList" :key="index">
							<u-checkbox
								:active-color="lightColor"
								label-size="25"
								v-model="item.checked"
								:name="item.value"
								:disabled="item.disabled"
							>
								{{ item.label }}
							</u-checkbox>
						</view>
					</view>
				</u-checkbox-group>
			</view>
		</u-popup>

		<uniMap v-if="mapFlag" @close="closeMap" @callback="callBackAddress" />
	</view>
</template>

<script>
import { applyThird } from "@/api/entry";
import { getCategoryList } from "@/api/goods";
import city from "@/components/m-city/m-city.vue";
import storage from "@/utils/storage.js";
import { upload } from "@/api/common.js";
import uniMap from "@/components/uniMap";
import permision from "@/js_sdk/wa-permission/permission.js";
export default {
	components: { "m-city": city, uniMap },
	data() {
		return {
			lightColor: this.$lightColor,
			storage,
			mapFlag: false,
			action: upload, //图片上传数据
			defaultInputStyle: {
				background: "#f7f7f7",
				padding: "0 20rpx",
				"border-radius": "10rpx"
			},
			goodsManagementCategory: "",
			type: "",
			storeLogoFileList: [],
			categoryList: [],
			typeList: [
				{
					label: "零售商",
					value: 1
				},
				{
					label: "批发商",
					value: 2
				},
				{
					label: "自营店",
					value: 3
				}
			],
			form: {
				storeName: "",
				storeLogo: "",
				type: "",
				goodsManagementCategory: "",
				storeAddressPath: "",
				storeAddressDetail: "",
				storeDesc: "",
				// 市场
				marketIds: ""
				// 提货地址
				// deliveryAddress: ""
			},
			list: [
				{
					id: "",
					localName: "请选择",
					children: []
				}
			],
			rules: {
				// 验证规则
				goodsManagementCategory: [{ required: true, message: "请选择店铺经营类目" }],
				type: [{ required: true, message: "请选择店铺类型" }],
				marketIds: [{ required: true, message: "请选择所属市场" }],
				storeName: [{ required: true, message: "请填写店铺名称" }],
				storeLogo: [{ required: true, message: "请上传店铺logo" }],
				storeDesc: [{ required: true, message: "请填写店铺简介" }],
				storeCenter: [{ required: true, message: "请选择店铺位置" }],
				storeAddressIdPath: [{ required: true, message: "请选择店铺位置" }],
				storeAddressDetail: [{ required: true, message: "请输入店铺详细地址" }]
			},
			enableCategory: false,
			enableType: false,
			marketVisible: false,
			marketList: JSON.parse(uni.getStorageSync("marketList")),
			marketIds: "",
			radioMarketId: "",
			checkboxMarketIds: []
		};
	},
	mounted() {
		this.$refs.uForm.setRules(this.rules);
		this.fetchCategoryList();
	},
	props: ["companyData"],
	watch: {
		companyData: {
			handler(val) {
				if (val && val.type === 0) {
					val.type = "";
				} else {
					this.type = this.typeList.find((item) => item.value == val.type).label;
					const arr = this.form.marketIds.split(",");
					if (arr) {
						this.marketIds = this.marketList
							.filter((item) => {
								return arr.indexOf(item.value) > -1;
							})
							.map((item) => item.label)
							.join(",");
					}
				}

				this.$set(this, "form", val);
				// 给图片赋值
				const judgeDeepPhoto = ["storeLogo"];

				judgeDeepPhoto.forEach((key) => {
					if (this.form[key]) {
						const images = typeof this.form[key] === "string" ? this.form[key].split(",") : this.form[key];
						images.forEach((item) => {
							this[`${key}FileList`].push({ url: item });
						});
					}
				});
			},
			deep: true,
			immediate: true
		}
	},

	methods: {
		callBackAddress(val) {
			this.form.storeAddressDetail = val.address;
			this.form.storeCenter = `${val.longitude},${val.latitude}`;
		},
		// 关闭地图
		closeMap() {
			this.mapFlag = false;
		},
		// 打开地图并访问权限
		clickUniMap() {
			// #ifdef APP-PLUS
			if (plus.os.name == "iOS") {
				// ios系统
				permision.judgeIosPermission("location") ? (this.mapFlag = true) : this.refuseMap();
			} else {
				// 安卓
				this.requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION");
			}
			// #endif

			// #ifndef APP-PLUS
			this.mapFlag = true;
			// #endif
		},

		// 如果拒绝权限 提示区设置
		refuseMap() {
			uni.showModal({
				title: "温馨提示",
				content: "您已拒绝定位,请开启",
				confirmText: "去设置",
				success(res) {
					if (res.confirm) {
						//打开授权设置
						// #ifndef MP-WEIXIN
						uni.getSystemInfo({
							success(res) {
								if (res.platform == "ios") {
									//IOS
									plus.runtime.openURL("app-settings://");
								} else if (res.platform == "android") {
									//安卓
									let main = plus.android.runtimeMainActivity();
									let Intent = plus.android.importClass("android.content.Intent");
									let mIntent = new Intent("android.settings.ACTION_SETTINGS");
									main.startActivity(mIntent);
								}
							}
						});
						// #endif
					}
				}
			});
		},
		// 获取安卓是否拥有地址权限
		async requestAndroidPermission(permisionID) {
			var result = await permision.requestAndroidPermission(permisionID);

			if (result == 1) {
				this.mapFlag = true;
			} else {
				this.refuseMap();
			}
		},

		confirmCategory(val) {
			this.form.goodsManagementCategory = val[0].value;
			this.goodsManagementCategory = val[0].label;
		},
		confirmType(val) {
			this.form.type = val[0].value;
			this.type = val[0].label;
			this.form.marketIds = "";
			this.marketIds = "";
		},
		async fetchCategoryList() {
			const res = await getCategoryList(0);
			if (res.data.success) {
				if (res.data.result.length) {
					this.categoryList = res.data.result.map((item) => {
						return { label: item.name, value: item.id };
					});

					if (this.form.goodsManagementCategory) {
						this.goodsManagementCategory = this.categoryList.find(
							(item) => this.form.goodsManagementCategory == item.value
						).label;
					}
				}
			}
		},
		// 图片上传
		onUploaded(lists, key) {
			let images = [];
			lists.forEach((item) => {
				images.push(item.response.result);
			});
			this.form[key] = images;
		},
		getPickerParentValue(e) {
			this.form.storeAddressIdPath = [];

			let name = "";
			e.forEach((item, index) => {
				if (item.id) {
					// 遍历数据
					this.form.storeAddressIdPath.push(item.id);
					if (index == e.length - 1) {
						name += item.localName;
					} else {
						name += item.localName + ",";
					}
					this.form.storeAddressPath = name;
				}
			});
		},
		// 显示三级地址联动
		showPicker() {
			this.$refs.cityPicker.show();
		},
		showCategory() {
			this.enableCategory = true;
		},
		showType() {
			this.enableType = true;
		},
		validatorStep1Form() {
			this.$refs.uForm.validate(async (valid) => {
				if (valid) {
					const params = { ...this.form };
					params.storeLogo = params.storeLogo.toString();
					params.storeAddressIdPath = params.storeAddressIdPath.toString();
					const res = await applyThird(params);
					if (res.data.success) {
						uni.showToast({
							title: "提交成功!",
							icon: "none"
						});
						this.$emit("callback", 1);
					}
				}
			});
		},
		nextStep() {
			this.$emit("callback", 0);
		},
		showMarket() {
			this.checkboxMarketIds = [];
			this.radioMarketId = "";
			(this.marketList = JSON.parse(uni.getStorageSync("marketList"))), (this.marketVisible = true);
		},
		radioChange(e) {
			this.radioMarketId = e;
		},
		checkboxGroupChange(e) {
			this.checkboxMarketIds = e;
			if (this.checkboxMarketIds.length >= 5) {
				this.marketList = this.marketList.map((item) => {
					if (this.checkboxMarketIds.indexOf(item.value) == -1) {
						item.disabled = true;
					}
					return item;
				});
			} else {
				this.marketList = this.marketList.map((item) => {
					item.disabled = false;
					return item;
				});
			}
		},
		cancelMarket() {
			this.marketVisible = false;
		},
		confirmMarket() {
			if (this.form.type == 2) {
				const marketIds = this.marketList
					.filter((item) => {
						return this.checkboxMarketIds.indexOf(item.value) > -1;
					})
					.map((item) => item.label);
				this.marketIds = marketIds.length ? marketIds.join(",") : "";
				this.form.marketIds = this.checkboxMarketIds.join(",");
			} else {
				const marketId = this.marketList.find((item) => item.value == this.radioMarketId);
				this.marketIds = marketId ? marketId.label : "";
				this.form.marketIds = this.radioMarketId;
			}
			this.marketVisible = false;
		}
	}
};
</script>
<style>
/* page {
  background: #fff;
} */
</style>
<style lang="scss" scoped>
@import url("./entry.scss");

.check-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 82rpx;
	padding: 0 40rpx;
	.check-left {
		color: rgb(96, 98, 102);
	}
	.check-right {
		color: rgb(41, 121, 255);
	}
}

.check-body {
	padding: 30rpx 40rpx;
	.radio-view {
		width: 100%;
		padding: 10rpx 0;
	}
}

.get-center {
	padding: 12rpx 30rpx;
	background: $light-color;
	border-radius: 10rpx;
	font-size: 24rpx;
	color: #fff;
	font-weight: bold;
	display: inline;
}

.column {
	padding: 32rpx;
	margin-bottom: 20rpx;
	background: #fff;
}

.submit {
	color: #fff;
	margin-top: 120rpx;
	background: rgba($light-color, 0.8);
}

.tips {
	color: #999;
	font-size: 24rpx;
	line-height: 1.2;
	margin-top: 10rpx;
}

.tips-success {
	color: $weChat-color;
	font-size: 24rpx;
}

.tip {
	color: $light-color;
	display: flex;
	justify-content: flex-end;
}
::v-deep {
	.no-del .u-delete-icon {
		display: none;
	}
}
</style>
